﻿using ConfExpert.Forms.ImportWizards;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevTeam;


using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo._7C
{
    public partial class NewOrderBig : XImportWizard
    {
        DataTable dtOrdine;
        DataTable dtAbb;

        public NewOrderBig()
        {
            InitializeComponent();
        }

        private void NewOrderBig_Load(object sender, EventArgs e)
        {
            dtDag = ExecuteDataTable("GetDagilimVertical2");

            this.ProcessDone += NewOrder_ProcessDone;
            this.ProcessStart += NewOrder_ProcessStart;
            this.FileDone += NewOrder_FileDone;


            btnSave.Enabled = false;
            btnSave.ItemClick += BtnSave_ItemClick;
        }

        void NewOrder_ProcessStart()
        {
            dtAbb = new DataTable();
            dtAbb.TableName = "Abb";
            dtAbb.Columns.Add("Modello", typeof(string));
            dtAbb.Columns.Add("Model", typeof(string));
            dtAbb.Columns.Add("Corpo", typeof(string));
            dtAbb.Columns.Add("Int1", typeof(string));
            dtAbb.Columns.Add("Int2", typeof(string));
            dtAbb.Columns.Add("Int3", typeof(string));
            dtAbb.Columns.Add("Int4", typeof(string));
            dtAbb.Columns.Add("Int5", typeof(string));
            dtAbb.Columns.Add("Gro", typeof(string));
            dtAbb.Columns.Add("Piping", typeof(string));
            dtAbb.Columns.Add("Profilo", typeof(string));
            dtAbb.Columns.Add("Bottone", typeof(string));
            dtAbb.Columns.Add("Filo", typeof(string));
            dtAbb.Columns.Add("Asola", typeof(string));
            dtAbb.Columns.Add("Travette", typeof(string));
            dtAbb.Columns.Add("Ricamo", typeof(string));
            dtAbb.Columns.Add("Travette_Vela", typeof(string));
            dtAbb.Columns.Add("Travetta_Finta", typeof(string));
            dtAbb.Columns.Add("Barkod", typeof(string));
            dtAbb.Columns.Add("AbbID", typeof(int));
            dtAbb.AddAutoIncrementalColumn("AbbID");
            //dtOrd.Columns["AbbID"].AutoIncrementSeed = -1;
            //dtOrd.Columns["AbbID"].AutoIncrementStep = -1;
            //dtOrd.Columns["AbbID"].AutoIncrement = true;
            dtAbb.PrimaryKey = new DataColumn[] { dtAbb.Columns["AbbID"] };


            dtOrdine = new DataTable();
            dtOrdine.TableName = "Ordine";
            dtOrdine.Columns.Add("Linea", typeof(string));
            dtOrdine.Columns.Add("Model", typeof(string));
            dtOrdine.Columns.Add("Corpo", typeof(string));
            dtOrdine.Columns.Add("Taglia", typeof(string));
            dtOrdine.Columns.Add("QtaPz", typeof(int));
            dtOrdine.Columns.Add("DagilimId", typeof(int));
            dtOrdine.Columns.Add("Pos", typeof(int));
            dtOrdine.Columns.Add("CodCliente", typeof(int));
            dtOrdine.Columns.Add("OrdineID", typeof(int));
            dtOrdine.AddAutoIncrementalColumn("OrdineID");
            //dtOrdine.Columns["OrdineID"].AutoIncrementSeed = 1;
            //dtOrdine.Columns["OrdineID"].AutoIncrement = true;
            dtOrdine.PrimaryKey = new DataColumn[] { dtOrdine.Columns["OrdineID"] };

            DataSet dsResult = new DataSet();
            dsResult.Tables.Add(dtAbb);
            dsResult.Tables.Add(dtOrdine);
        }

        void NewOrder_FileDone(DataSet ds, string FileName)
        {
            dtAbb.Clear();
            dtOrdine.Clear();

            for (int i = 0; i < ds.Tables.Count; i++)
            {
                DataTable dt = ds.Tables[i];

                if (dt.TableName.StartsWith("Abb"))
                    ProcessAbb(dt);

                else if (dt.TableName.StartsWith("Ordine"))
                    ProcessOrdine(dt);
            }
        }

        void NewOrder_ProcessDone()
        {
            string xmla = dtAbb.Serialize();
            string xmlo = dtOrdine.Serialize();

            DataSet d = ExecuteDataSet("GetGPNewOrderBig", xmla, xmlo);
            DataSet kart = new DataSet();
            DataSet model = new DataSet();

            kart.Tables.Add(d.Tables[2].Copy());
            kart.Tables.Add(d.Tables[3].Copy());

            model.Tables.Add(d.Tables[4].Copy());
            model.Tables.Add(d.Tables[5].Copy());

            gvSip2.Init(d.Tables[0].Copy());
            gvAbbinamenti.Init(d.Tables[1].Copy());

            gvKart2.Init(kart.Tables[0]);
            gvKart2.AddDetailGrid(gvKartlar2, "idx");
            gvKartlar2.MakeColumnInvisible("idx");

            gvModel2.Init(model.Tables[0]);
            gvModel2.AddDetailGrid(gvModeller2, "M");
            gvModel2.MakeColumnInvisible("M");

            RepositoryItemProgressBar riProgress = new RepositoryItemProgressBar();
            riProgress.ShowTitle = true;
            riProgress.PercentView = true;
            riProgress.Maximum = 100;

            gvModeller2.Columns["Score"].ColumnEdit = riProgress;
            gvKartlar2.Columns["Score"].ColumnEdit = riProgress;

            gvAbbinamenti.MakeReadOnly();
            gvModel2.MakeReadOnly("Linea");
            gvModeller2.MakeReadOnly();
            gvKart2.MakeReadOnly("Art");
            gvKartlar2.MakeReadOnly();

            gvSip2.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gvSip2.ClearColumnEdit("CKBatchId");

            gvModeller2.RowStyle += gvModeller_RowStyle;

            RepositoryItemComboBox riLinea = new RepositoryItemComboBox();
            riLinea.Items.AddRange(new object[] { "BAMBINO", "DONNA", "UOMO" });
            riLinea.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            gvModel2.Columns["Linea"].ColumnEdit = riLinea;

            gvModeller2.AddColumn("Esleme", typeof(string));
            gvModeller2.MakeColumnInvisible("M", "Esleme");
            gvModel2.AddColumn("Eşleme", typeof(string), "MAX(Child({FK}).Esleme)");

            gvSip2.MakeRowSelectable();
            gvModeller2.MakeRowSelectable();
            gvModeller2.DoubleClick += gvModeller_DoubleClick;

            BestFitGrids(gvModel2, gvModeller2, gvSip2, gvKart2, gvKartlar2, gvAbbinamenti);

            gvModel2.Columns["Linea"].Width = 70;
            gvModel2.FormatAsNumber(0, "QtaPz");
            gvModel2.AddSummary("QtaPz");

            //gvSource.BestFitColumns();
            btnSave.Enabled = true;
            gvModeller2.OptionsView.EnableAppearanceEvenRow = gvModeller2.OptionsView.EnableAppearanceOddRow = false;
            gvSip2.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
            gvSip2.MakeRowVisible(gvSip2.FocusedRowHandle);
        }

        void gvModeller_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView gv = (sender as GridView);
            if (e.RowHandle > -1)
                if (gv.Columns.Contains(gv.Columns["Esleme"]))
                    if (gv.GetRowCellDisplayText(e.RowHandle, "Esleme") == "E")
                        e.Appearance.BackColor = Color.YellowGreen;
                    else
                        e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
        }

        void gvModeller_DoubleClick(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;
            Point pt = view.GridControl.PointToClient(Control.MousePosition);
            GridHitInfo info = view.CalcHitInfo(pt);
            if (info.InRow || info.InRowCell)
                if (info.RowHandle > -1)
                {
                    int E = view.LocateByDisplayText(0, view.Columns["Esleme"], "E");
                    if (E > -1)
                        view.SetRowCellValue(E, "Esleme", null);

                    if (info.RowHandle != E)
                        view.SetFocusedRowCellValue("Esleme", "E");
                }
            //string colCaption = info.Column == null ? "N/A" : info.Column.GetCaption();
            view.EndEditing();
        }





        void gvKartlar_RowStyle(object sender, RowStyleEventArgs e)
        {
            GridView gv = (sender as GridView);
            if (e.RowHandle > -1)
                if (!gv.GetRowCellDisplayText(e.RowHandle, "Art").Contains("/"))
                    e.Appearance.BackColor = Color.DeepSkyBlue;
                else
                    e.Appearance.Combine((e.RowHandle & 1) != 0 ? gv.Appearance.EvenRow : gv.Appearance.OddRow);
        }

        void BestFitGrids(params GridView[] gvs)
        {
            foreach (GridView gv in gvs)
            {
                gv.AddSummary();
                gv.BestFitColumns();
            }
        }

        Dictionary<string, int> colsAbb = new Dictionary<string, int>();
        Dictionary<string, int> colsOrdine = new Dictionary<string, int>();
        DataTable dtDag;
        private void ProcessAbb(DataTable dt)
        {
            colsAbb.Clear();
            for (int i = 0; i < dt.Columns.Count; i++)
                colsAbb[dt.Rows[0][i].ToStr()] = i;

            for (int i = 1; i < dt.Rows.Count; i++)
            {
                {
                    string firstCell = dt.Rows[i][0].ToStr();

                    if (firstCell == "")
                        continue;
                    else
                    {
                        DataRow newRowA = dtAbb.NewRow();
                        foreach (DataColumn dc in dtAbb.Columns)
                            if (dc.Caption != "AbbID")
                                newRowA[dc.Caption] = GetVal(dt.Rows[i], dc.Caption);

                        string Corpo = newRowA["Corpo"].ToStr();
                        string Model = newRowA["Model"].ToStr(); //.Replace(newRowA["Corpo"].ToStr(), string.Empty);
                        if (Model == string.Empty)
                            Model = newRowA["Modello"].ToStr().Replace(Corpo, string.Empty);

                        if (!Model.StartsWith("SF"))
                            Model = "SF" + Model;

                        newRowA["Model"] = Model;

                        if (Corpo == "")
                            continue;

                        dtAbb.Rows.Add(newRowA);
                    }
                }
            }
        }


        object GetVal(DataRow dr, string Caption)
        {
            if (colsAbb.ContainsKey(Caption))
            {
                int idx = colsAbb[Caption];
                if (dr[idx] != null)
                    if (dr[idx] != DBNull.Value)
                    {
                        string o = dr[idx].ToStr();

                        if (o != "-")
                            if (dr.Table.Columns[idx].DataType == typeof(string))
                            {
                                if (o != null)
                                    if (Caption.StartsWith("Int") || Caption.StartsWith("Profilo") || Caption.StartsWith("Gro"))
                                    {
                                        if (o.StartsWith("PS0002UN") ||
                                        o.StartsWith("SN0001UN") ||
                                        o.StartsWith("JNL070UN"))
                                            return "GRN." + o;

                                        if (o.StartsWith("PF0091UN"))
                                            return "GRN." + o.Replace("PF0091UN", "PS0002UN");

                                    }
                                return o;
                            }
                            else if (dr.Table.Columns[idx].DataType == typeof(int))
                                return o.ToInt();
                    }
            }

            return DBNull.Value;
        }

        object GetValOrd(DataRow dr, string Caption)
        {
            if (colsOrdine.ContainsKey(Caption))
            {
                int idx = colsOrdine[Caption];
                if (dr[idx] != null)
                    if (dr[idx] != DBNull.Value)
                    {
                        object o = dr[idx].ToStr();

                        if (o.ToStr() != "-")
                            if (dr.Table.Columns[idx].DataType == typeof(string))
                                return o;
                            else if (dr.Table.Columns[idx].DataType == typeof(int))
                                return o.ToInt();
                    }
            }

            return DBNull.Value;
        }

        private void ProcessOrdine(DataTable dt)
        {
            colsOrdine.Clear();
            for (int i = 0; i < dt.Columns.Count; i++)
                colsOrdine[dt.Rows[0][i].ToStr()] = i;

            for (int i = 1; i < dt.Rows.Count; i++)
            {
                string firstCell = dt.Rows[i][0].ToStr();

                if (firstCell == "")
                    continue;
                else
                {
                    DataRow newRowA = dtOrdine.NewRow();
                    foreach (DataColumn dc in dtOrdine.Columns)
                        if (dc.Caption != "OrdineID")
                            newRowA[dc.Caption] = GetValOrd(dt.Rows[i], dc.Caption);

                    string Corpo = newRowA["Corpo"].ToStr();
                    string Model = newRowA["Model"].ToStr(); //.Replace(newRowA["Corpo"].ToStr(), string.Empty);
                    if (!Model.StartsWith("SF"))
                        Model = "SF" + Model;

                    newRowA["Model"] = Model;

                    if (Corpo == "")
                        continue;

                    string Tg = newRowA["Taglia"].ToStr();

                    //TODO!
                    //if (Tg == "XXXL")
                    //    Tg = "3XL";
                    if (Tg == "2XL")
                        Tg = "XXL";

                    /*
                     * select distinct dagilimId, linea from gpord o
INNER JOIN gpabb a ON o.modello = a.modello
where a.CKBatchId = 30 and o.CKBatchId = 30
*/
                    int DagilimId = 0;
                    string Linea = newRowA["Linea"].ToStr();
                    switch (Linea)
                    {
                        case "U":
                        case "UOMO":
                            newRowA["Linea"] = "UOMO";
                            DagilimId = 10; //7; 
                            break;

                        case "D":
                        case "DONNA":
                            newRowA["Linea"] = "DONNA";
                            DagilimId = 12;
                            break;

                        case "B":
                        case "BAMBINO":
                            newRowA["Linea"] = "BAMBINO";
                            DagilimId = 4;
                            break;
                    }

                    newRowA["DagilimId"] = DagilimId;   //TODO: önce abb. okunması gerekiyor dağılımId'lerin dolması için!
                    newRowA["Pos"] = dtDag.Select("DagilimId=" + DagilimId.ToString() + " AND Beden='" + Tg + "'")[0]["Pos"];  //caption verilen dağılım içinde yoksa exception verir!

                    dtOrdine.Rows.Add(newRowA);
                }

            }

        }

        private void BtnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvSip2.EndEditing();

            DataRow r = gvSip2.GetFocusedDataRow();
            int BrandId = r["BrandId"].ToInt();
            int SezonId = r["SezonId"].ToInt();
            string Notes = r["Notes"].ToStr();

            string xmlK = gvKart2.DataTable().Serialize();

            DataTable dt = new DataTable("Model");
            dt.Columns.Add("Model", typeof(string));
            dt.Columns.Add("Linea", typeof(string));
            dt.Columns.Add("CKBatchId", typeof(int));
            dt.Columns.Add("M", typeof(string));

            DataTable tm = gvModeller2.DataTable();

            foreach (DataRow r2 in gvModel2.DataTable().Rows)
            {
                DataRow nr = dt.NewRow();
                string Model = r2["Model"].ToStr();
                nr["Model"] = Model;
                nr["Linea"] = r2["Linea"];

                DataRow[] rx = tm.Select("M='" + Model + "' AND Esleme='E'");
                if (rx.Length > 0)
                {
                    nr["M"] = rx[0]["Model"];
                    nr["CKBatchId"] = rx[0]["CKBatchId"];
                }
                dt.Rows.Add(nr);
            }

            string xmlM = dt.Serialize();
            string xmlA = dtAbb.Serialize();
            string xmlO = dtOrdine.Serialize();

            string ret = ExecuteScalar("InsGPNewOrderBig", BrandId, SezonId, Notes, xmlK, xmlM,
                dtAbb.Serialize(), dtOrdine.Serialize(), WhoAmI).ToString();

            ShowInfoMessage(ret);

            btnSave.Enabled = !ret.Contains("başarı");

        }

    }
}
